package com.android.qjpmc.application_module.home.fragment;

import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.home.contract.AlarmRecordContract;
import com.android.qjpmc.application_module.home.viewModel.HomeViewModel;
import com.android.qjpmc.application_module.pop.ListCheckPopupWindow;
import com.android.qjpmc.bean.AlarmRecordItemBean;
import com.android.qjpmc.bean.ListCheckPopBean;
import com.android.qjpmc.bean.PointParameterBean;
import com.android.qjpmc.bean.PwrDeviceBean;
import com.android.qjpmc.bean.SiteStationBean;
import com.android.qjpmc.constant.Constant;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.data_module.PwrStation;
import com.android.qjpmc.databinding.FragmentAlarmRecordItemBinding;
import com.android.qjpmc.databinding.FragmentAlarmRecordsBinding;
import com.android.qjpmc.manager.IntentManager;
import com.android.qjpmc.application_module.home.viewModel.AlarmRecordsViewModel;
import com.android.qjpmc.widget.databindingadapter.BaseBindingItemPresenter;
import com.android.qjpmc.widget.databindingadapter.BaseDataBindingDecorator;
import com.android.qjpmc.widget.databindingadapter.SingleTypeBindingAdapter;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.mvvm.view.BaseMVVMFragment;
import com.android.qjpmc.widget.utils.TimeUtils;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CreateViewModel(AlarmRecordsViewModel.class)
public class AlarmRecordslFragment extends BaseMVVMFragment<AlarmRecordsViewModel, FragmentAlarmRecordsBinding> implements AlarmRecordContract.View, BaseBindingItemPresenter {

    PwrStation m_the_power_station = null;
    private List<SiteStationBean> companys;

    PwrStation GetThePwrStation() {
        return m_the_power_station;
    }

    void SetPwrStation(PwrStation station) {
        m_the_power_station = station;
    }

    String m_start_time;
    String m_end_time;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_alarm_records;
    }

    @Override
    public void initView() {
        mBinding.setView(this);

    }

    @Override
    public void initData() {
        mViewModel.getStationList();
        PwrDataModule.getInstance().SetAlarmFragement(this);
    }

    @Override
    public void initEvent() {

    }


    public void openData() {


    }

    private ListCheckPopupWindow companyListPopupWindow;
    private ListCheckPopupWindow deviceListPopupWindow;
    private ListCheckPopupWindow levelListPopupWindow;
    SiteStationBean selectCompany = new SiteStationBean("-1");
    PwrDeviceBean selectDevice = new PwrDeviceBean("-1");
    ListCheckPopBean selectLevel = new ListCheckPopBean("-1");

    public void onCheckCompany() {
        if (companyListPopupWindow == null) {
            companyListPopupWindow = new ListCheckPopupWindow((FragmentActivity) getContext());
            List<ListCheckPopBean> popListData = new ArrayList<>();
            if (companys != null) {
                for (SiteStationBean company : companys) {
                    popListData.add(new ListCheckPopBean(company.company_id, company.company_name, false));
                }
            }
            popListData.add(0, new ListCheckPopBean("-1", "全部", false));

            companyListPopupWindow.initListData(popListData);
            companyListPopupWindow.setListCheckPopupWindowListener(new ListCheckPopupWindow.ListCheckPopupWindowListener() {
                @Override
                public void onPopChooseResult(List<ListCheckPopBean> popListData) {
                    selectCompany = null;
                    for (ListCheckPopBean popListDatum : popListData) {
                        if (popListDatum.isOpen) {
                            if (!popListDatum.id.equals("-1")) {
                                for (SiteStationBean company : companys) {
                                    if (popListDatum.id.equals(company.company_id)) {
                                        selectCompany = company;
                                        break;
                                    }
                                }
                            } else {
                                selectCompany = new SiteStationBean("-1");
                                break;
                            }
                        }
                    }
                    if (selectCompany == null) {
                        mBinding.tvCompanyName.setText("请选择站点");
                    } else {
                        if (selectCompany.company_id.equals("-1")) {
                            mBinding.tvCompanyName.setText("查看全部");
                            mBinding.tvDeviceName.setText("查看全部");
                        } else {
                            mBinding.tvCompanyName.setText(selectCompany.company_name);

                        }

                    }
                }
            });
        }
        View view = mActivity.getWindow().getDecorView();
        companyListPopupWindow.showPopupWindowAtLocation(view);


    }

    public void onCheckDevice() {
        if (selectCompany == null) {
            ToastUtils.showShort("请先选择站点");
            return;
        }
        if (selectCompany.company_id.equals("-1")) {
            ToastUtils.showShort("站点选择查看全部,设备默认查看全部,不需要选择");
            return;
        }
        mViewModel.getGroupListOfStation(selectCompany.company_id);


    }

    public void onCheckLevel() {
        if (levelListPopupWindow == null) {
            levelListPopupWindow = new ListCheckPopupWindow((FragmentActivity) getContext());
            List<ListCheckPopBean> popListData = new ArrayList<>();
            popListData.add(new ListCheckPopBean("-1", "查看全部", false));
            popListData.add(new ListCheckPopBean("1", "1级", false));
            popListData.add(new ListCheckPopBean("2", "2级", false));
            popListData.add(new ListCheckPopBean("3", "3级", false));
            popListData.add(new ListCheckPopBean("4", "4级", false));
            levelListPopupWindow.initListData(popListData);
            levelListPopupWindow.setListCheckPopupWindowListener(new ListCheckPopupWindow.ListCheckPopupWindowListener() {
                @Override
                public void onPopChooseResult(List<ListCheckPopBean> popListData) {
                    for (ListCheckPopBean popListDatum : popListData) {
                        if (popListDatum.isOpen) {
                            selectLevel = popListDatum;
                            break;
                        }
                    }
                    if (selectLevel == null) {
                        mBinding.tvAlarmLevel.setText("请选择报警等级");
                    } else {
                        mBinding.tvAlarmLevel.setText(selectLevel.id.equals("-1") ? "查看全部" : selectLevel.name);

                    }
                }
            });
        }
        View view = mActivity.getWindow().getDecorView();
        levelListPopupWindow.showPopupWindowAtLocation(view);


    }


    public void onQueryRecordData() {
        //todo 胖胖注释的
        // UpdataValuesText();
        if (selectCompany == null) {
            ToastUtils.showShort("请选择站点");
            return;
        }
        if (selectDevice == null) {
            ToastUtils.showShort("请选择设备");
            return;
        }
        if (selectLevel == null) {
            ToastUtils.showShort("请选择报警等级");
            return;
        }
        if (TextUtils.isEmpty(m_start_time)) {
            ToastUtils.showShort("请选择数据开始时间");
            return;
        }
        if (TextUtils.isEmpty(m_end_time)) {
            ToastUtils.showShort("请选择数据结束时间");
            return;
        }

        long startTimeLong = TimeUtils.parsDataTimeLong(m_start_time, TimeUtils.DEFAULT_SDF);
        long endTimeLong = TimeUtils.parsDataTimeLong(m_end_time, TimeUtils.DEFAULT_SDF);
        if (startTimeLong >= endTimeLong) {
            ToastUtils.showShort("开始时间不能大于结束时间");
            return;
        }
        /*
        * alarm_time-0: "2023-04-04 00:06:14"
alarm_time-1: "2023-05-04 00:06:14"
alarm_time-op: "bt"
order: "desc"
sort: "alarm_time"*/
        Map<String, Object> queryParams = new HashMap();
        queryParams.put("alarm_time-0", m_start_time);
        queryParams.put("alarm_time-1", m_end_time);
        List<String> alarmTime = new ArrayList<>();
        alarmTime.add(m_start_time);
        alarmTime.add(m_end_time);
        queryParams.put("alarm_time", alarmTime);
        queryParams.put("alarm_time-op", "bt");
        queryParams.put("order", "desc");
        queryParams.put("sort", "alarm_time");
        if (!selectLevel.id.equals("-1")) {
            queryParams.put("alarm_level", selectLevel.id);
        }
        if (!selectDevice.groupId.equals("-1")) {
            queryParams.put("device_code", selectDevice.deviceCode);
        }
        if (!selectCompany.company_id.equals("-1")) {
            queryParams.put("company_code", selectCompany.companyCode);
        }
        mViewModel.getAlarmRecordList(queryParams);
    }

    @Override
    public void returnAlarmRecordList(List<AlarmRecordItemBean> alarmRecords) {
        UpdataValuesText(alarmRecords);
    }

    public void onWaringDetails() {
        IntentManager.toAlarmRecordDetailActivity(getContext());
    }

    void UpdataValuesText(List<AlarmRecordItemBean> alarmRecords) {
        //if ( (m_thePwrDevice != null) && (m_CurrentPwrStation != null) )
        {
            //todo 胖胖注释的
            // ArrayList<AlarmRecordItemBean> AnalogList = PwrDataModule.getInstance().GetAlarmRecordDataArray();//PwrDataModule.getInstance().GetAnalogDataList(m_CurrentPwrStation.getM_ID(), m_thePwrDevice.GetID() );
            SingleTypeBindingAdapter adapter = new SingleTypeBindingAdapter(getContext(), alarmRecords, R.layout.fragment_alarm_record_item);
            mBinding.rtDataList.setAdapter(adapter);

            adapter.setItemPresenter(this);

            mBinding.rtDataList.setLayoutManager(new LinearLayoutManager(getContext()));


            adapter.setItemDecorator(new BaseDataBindingDecorator<AlarmRecordItemBean, FragmentAlarmRecordItemBinding>() {

                @Override
                public void decorator(FragmentAlarmRecordItemBinding binding, int position, int viewType, AlarmRecordItemBean data) {
                 /*   binding.time.setText(data.m_time);
                    binding.position.setText(data.m_name);
                    binding.value.setText(data.m_value_text);
                    binding.faultValue.setText(data.m_fault_value);*/
                    binding.tvTime.setText(data.alarm_time);
                    binding.tvCompanyName.setText(data.company_name);
                    binding.tvDeviceName.setText(data.device_name);
                    binding.tvLevel.setText(String.valueOf(data.alarm_level));
                    binding.tvContent.setText(data.alarm_content);
                    binding.tvStatus.setText(data.alarm_status.equals("u") ? "严重报警" : "普通警告");
                }
            });
        }
    }

    @Override
    public void onItemClick(int position, Object itemData) {

    }

    TimePickerView pvStartTime;
    TimePickerView pvEndTime;

    public void onSelectStartTime() {
        if (pvStartTime == null) {
            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());
            pvStartTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_start_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvStartTime.setText(m_start_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate).setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }
        pvStartTime.show();
    }

    public void onSelectEndTime() {
        if (pvEndTime == null) {
            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());
            pvEndTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_end_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvEndTime.setText(m_end_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate)
                    .setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }
        pvEndTime.show();
    }


    private Handler m_handler = new Handler();
    Runnable m_UpdateUIRunnable = new Runnable() {
        @Override
        public void run() {
//            InitializeStationSpinner();
        }
    };

    public int UpdateStationListUI() {
        if (m_handler == null) {
            return Constant.GEN_ERROR;
        }
        m_handler.post(m_UpdateUIRunnable);
        return Constant.NO_ERROR;
    }

    @Override
    public void returnSiteStationData(List<SiteStationBean> siteStationBeans) {
        this.companys = siteStationBeans;

    }


    @Override
    public void returnCompanyDevicesListData(List<PwrDeviceBean> siteStationBeans) {
        if (siteStationBeans == null) {
            ToastUtils.showShort("该站点下没有设备可以选择");
            return;
        }
        deviceListPopupWindow = new ListCheckPopupWindow((FragmentActivity) getContext());
        List<ListCheckPopBean> popListData = new ArrayList<>();
        for (PwrDeviceBean deviceBean : siteStationBeans) {
            popListData.add(new ListCheckPopBean(deviceBean.groupId, deviceBean.deviceName, false));
        }
        popListData.add(0, new ListCheckPopBean("-1", "全部", false));
        deviceListPopupWindow.initListData(popListData);
        deviceListPopupWindow.setListCheckPopupWindowListener(new ListCheckPopupWindow.ListCheckPopupWindowListener() {
            @Override
            public void onPopChooseResult(List<ListCheckPopBean> popListData) {
                selectDevice = null;
                for (ListCheckPopBean popListDatum : popListData) {
                    for (PwrDeviceBean deviceBean : siteStationBeans) {
                        if (popListDatum.isOpen) {
                            if (popListDatum.id.equals("-1")) {
                                PwrDeviceBean allDeviceTemp = new PwrDeviceBean();
                                allDeviceTemp.groupId = "-1";
                                selectDevice = allDeviceTemp;
                                break;
                            } else {
                                if (popListDatum.id.equals(deviceBean.groupId)) {
                                    selectDevice = deviceBean;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (selectDevice == null) {
                    mBinding.tvDeviceName.setText("请选择设备");
                } else {
                    mBinding.tvDeviceName.setText(selectDevice.groupId.equals("-1") ? "查看全部" : selectDevice.deviceName);

                }
            }
        });
        View view = mActivity.getWindow().getDecorView();
        deviceListPopupWindow.showPopupWindowAtLocation(view);


    }
}
